using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.WriteApi.Appcontext.Command;
using Yitter.IdGenerator;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class AssignRolesToEmployeeCommandHandler : IRequestHandler<AssignRolesToEmployeeCommand, bool>
	{
		private readonly IBaseRepository<EmployeeRole> _erRepo;

		public AssignRolesToEmployeeCommandHandler(IBaseRepository<EmployeeRole> erRepo)
		{
			_erRepo = erRepo;
		}

		public async Task<bool> Handle(AssignRolesToEmployeeCommand request, CancellationToken cancellationToken)
		{
			var olds = _erRepo.GetAll().Where(x => ((EmployeeRole)x).EmployeeId == request.EmployeeId).Select(x => (EmployeeRole)x).ToList();
			if (olds.Count > 0) await _erRepo.DeleteRangeAsync(olds);
			var news = request.RoleIds.Distinct().Select(rid => new EmployeeRole { EmployeeRoleId = YitIdHelper.NextId(), EmployeeId = request.EmployeeId, RoleId = rid }).ToList();
			if (news.Count > 0) await _erRepo.AddRangeAsync(news);
			return true;
		}
	}
}
